package com.renjun.smweb.service.AdminService.impl;

import com.alibaba.fastjson.JSONObject;
import com.renjun.smweb.commons.componet.BaseDaoComponent;
import com.renjun.smweb.commons.componet.FileIOComponent;
import com.renjun.smweb.commons.enums.EOperators;
import com.renjun.smweb.commons.enums.EStandTables;
import com.renjun.smweb.commons.global.DataDict;
import com.renjun.smweb.commons.global.DataMap;
import com.renjun.smweb.commons.util.*;
import com.renjun.smweb.dao.BaseDao;
import com.renjun.smweb.dao.bean.InsertParams;
import com.renjun.smweb.dao.bean.Parameter;
import com.renjun.smweb.dao.bean.QueryParams;
import com.renjun.smweb.dao.bean.UpdateParams;
import com.renjun.smweb.dao.pojo.LoginInfo;
import com.renjun.smweb.service.AdminService.AdminService;
import com.renjun.smweb.commons.componet.BaseDaoComponent;
import com.renjun.smweb.commons.global.FileInfoPo;
import com.renjun.smweb.dao.bean.InsertParams;
import com.renjun.smweb.dao.bean.Parameter;
import com.renjun.smweb.exceptions.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.renjun.smweb.commons.util.BaseChecks.hasNullObject;
import static com.renjun.smweb.dao.bean.Parameter.createParameter;

/**
 * Created by huamin on 2017/2/21.
 */
@Service
public class AdminServiceImpl implements AdminService {
    @Autowired
    private BaseDaoComponent baseDaoComponent;

    /** 登陆 **/
    public JSONObject login(Map<String, Object> params,HttpServletRequest request) throws SQLException, BaseException {
        JSONObject rs = new JSONObject();
        HttpSession session = request.getSession();
        session.setMaxInactiveInterval(60*60*24);//1小时//以秒为单位
        params.put("validateNum", session.getAttribute("validateNum"));
        if (session == null) {
            rs.put("message", "非法登录");
            return rs;
        }
        // 前端报文结构 {name:用户名,pwd:明文密码,vcode:验证码}
        Object pwd = params.get("pwd");   //目前pwd是明文
        String ename = (String) params.get("ename");
        Object vcode = params.get("vcode");
        String mpwd = Encrypt.jiam((String)pwd);    //md5加密后的密码

        if (hasNullObject(pwd, ename, vcode)) {
            return ResponseUtils.createErrorResponseBody("输入的数据不完整");
        }
        String validateNum = (String) params.get("validateNum");
        if (validateNum != null && vcode != null && vcode.toString().equalsIgnoreCase(validateNum)) {//验证码正确
            //用户名密码，sql拼接
            QueryParams queryParams = QueryParams.createQueryParams("V_M49_LOGIN_NK");
            queryParams.addQueryParams(Parameter.createParameter("ENAME", ename), Parameter.createParameter("CIPHERTEXTMD", mpwd));
    //        queryParams.addQueryParams(createParameter("ENAME", ename), createParameter("CIPHERTEXT", pwd));
            queryParams.printSelf();
            //执行sql返回map集合数据
            List<Map<String, Object>> data = baseDaoComponent.selectDataByParams(queryParams);
            if (data.size() == 0) {
                throw new LoginPwdException();
            }
            String id = (String) data.get(0).get("id");
            LoginInfo userInfo = createUserInfo(id, ename);

            String pwdstatus = "0";
        /*    String dePwd = Encrypt.strDecode(pwd.toString());
            if (!checkPwdRule(dePwd)) {
                pwdstatus = "1";
            }*/
            if (!checkPwdRule((String) pwd)) {
                pwdstatus = "1";
            }
            String modifyPassWordTime = (String) data.get(0).get("modifyPassWordTime");
            if(!"".equals(modifyPassWordTime)&&null!=modifyPassWordTime) {
                userInfo.setModifyPassWordTime(Format.getDateLong(modifyPassWordTime));
            }
            userInfo.setPwdstatus(pwdstatus);
            session.setAttribute("userinfo", userInfo);
            rs = ResponseUtils.createSuccessResponseBody(userInfo);
            return rs;
        } else {
            throw new LaunchCommitException(80001);
        }
    }

    private boolean checkPwdRule(String pwd) {
        boolean hasChar = false;
        boolean hasNum = false;
        if (pwd.length() < 8) return false;
        for (int i = 0, len = pwd.length(); i < len; i++) {
            String ch = pwd.substring(i, i + 1);
            if (!hasChar && ch.matches("\\w")) {
                hasChar = true;
                continue;
            }
            if (!hasNum && ch.matches("\\d")) {
                hasNum = true;
                continue;
            }
        }
        return hasChar && hasNum;
    }

    private LoginInfo createUserInfo(String userId, String ename) throws BaseException, SQLException {
        LoginInfo userInfo = null;
        try {
            userInfo = getLoginInfoByUserId(userId, userId, ename);
            if ("1".equalsIgnoreCase(userInfo.getDeleted())) throw new BaseException(90001);
        } catch (InvocationTargetException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return userInfo;
    }

    public LoginInfo getLoginInfoByUserId(String userId, String operId, String operName) throws SQLException, BaseException, InvocationTargetException, IllegalAccessException {
        QueryParams userInfo = QueryParams.createQueryParams("V_M49_getLoginInfoByUserId_NK");
        userInfo.addQueryParams(Parameter.createParameter("ID", userId));
        userInfo.addQueryParams(Parameter.createParameter("deleted", "0"));
        userInfo.addQueryParams(Parameter.createParameter("schoolDeleted","0"));
        List<Map<String, Object>> user = baseDaoComponent.selectDataByParams(userInfo);
    //    if (user == null || user.size() == 0) throw new DataNotFoundException();
        if (user == null || user.size() == 0) throw new BaseException(80003);
        Map<String, Object> currentUser = user.get(0);
        currentUser.put("operid",operId);
        currentUser.put("opername",operName);
        LoginInfo loginInfo = LoginInfo.createLoginInfoByMap(currentUser);
        return loginInfo;
    }

    /** 用户列表 **/
    @Override
    public JSONObject queryAdminUserList(Map<String, Object> params) throws SQLException, DataNotFoundException {
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        QueryParams queryParams = QueryParams.createQueryParams("V_M41_ADMINLIST_NK");
        //要remove字段就会改变map大小,因此需要另外再给个map集合
        String realName = (String) params.remove("realname");   //获得要查询的姓名
        String ename = (String) params.remove("ename");    //获得要查询的用户名
        String mobile = (String) params.remove("mobile");   //手机号
        if("username".equals(params.get("sort"))){
            params.put("sort","ename");
        }
        Map<String,Object> map = new DataMap<>();
        for(Map.Entry<String,Object> m:params.entrySet()){
            if(m.getValue()!=null&&!m.getValue().toString().isEmpty())
                map.put(m.getKey(),m.getValue());
        }
        queryParams.addQueryParamsByMap(map);
        //验证是否为空加入模糊查询
        if(!BaseChecks.hasEmptyStr(realName)){      //姓名模糊查询
            //判断是否为中文
            if(BaseChecks.isChineseChar(realName)){
                //是，空格全部替换
                realName = realName.replaceAll(" ","");
            }else{
                //否，替换两端空格
                realName = BaseChecks.bothEndsStr(realName);
            }
            queryParams.addQueryParams(Parameter.createParameter("realname", EOperators.类似, BaseChecks.bothEndsStr(realName)));
        }
        if(!BaseChecks.hasEmptyStr(ename)){      //用户名模糊查询
            //判断是否为中文
            if(BaseChecks.isChineseChar(ename)){
                //是，空格全部替换
                ename = ename.replaceAll(" ","");
            }else{
                //否，替换两端空格
                ename = BaseChecks.bothEndsStr(ename);
            }
            queryParams.addQueryParams(Parameter.createParameter("ename", EOperators.类似, BaseChecks.bothEndsStr(ename)));
        }
        if(!BaseChecks.hasEmptyStr(mobile))queryParams.addQueryParams(Parameter.createParameter("MOBILE",EOperators.类似,BaseChecks.bothEndsStr(mobile)));
        queryParams.printSelf();
        try {
            queryParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> result = baseDaoComponent.selectDataByParams(queryParams);
        JSONObject rs = ResponseUtils.createSuccessResponseBody("done", result);
        if(!result.isEmpty()) rs.put("total",result.get(0).get("total"));
        //如果是市管理员，需统计区管理员状态信息
        if("1".equals(loginInfo.getRoletype())){
            QueryParams queryParams1 = QueryParams.createQueryParams("V_M41_ADMINLIST_NK");
            queryParams1.sethasColums(true);
            queryParams1.addQueryParams(Parameter.createParameter("deleted","0"),Parameter.createParameter("roletype","2"));
            queryParams1.addColumns("sum(ID) as a");   //启用的
            try {
                queryParams1.setDbLog(loginInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            queryParams1.printSelf();
            List<Map<String, Object>> result1 = baseDaoComponent.selectDataByParams(queryParams1);
            if(!result1.isEmpty()){
                rs.put("notdelete",result1.get(0).get("a"));
            }
            QueryParams queryParams2 = QueryParams.createQueryParams("V_M41_ADMINLIST_NK");
            queryParams2.sethasColums(true);
            queryParams2.addQueryParams(Parameter.createParameter("deleted","1"),Parameter.createParameter("roletype","2"));
            queryParams2.addColumns("sum(ID) as a");   //停用的
            try {
                queryParams2.setDbLog(loginInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            queryParams2.printSelf();
            List<Map<String, Object>> result2 = baseDaoComponent.selectDataByParams(queryParams2);
            if(!result2.isEmpty()){
                rs.put("delete",result2.get(0).get("a"));
            }
        }
        return rs;
    }

    /** 导出用户列表 **/
    @Override
    public JSONObject expAdminUserList(Map<String, Object> params) throws SQLException, DataNotFoundException, IOException, FileTypeNotFoundException {
        //查询用户列表
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        params.remove("sort");
        params.remove("offset");

        String xm = (String) params.remove("realname");
        List<Parameter> list = Parameter.createParameters(params);
        QueryParams queryParams = QueryParams.createQueryParams("V_M41_ADMINLIST_NK");
        for (Parameter p : list) {
            if (p.getColumnName().trim().equals("order") || p.getColumnName().trim().equals("limit")) {
                continue;
            }
            if(p.getDataValues().get(0).getValue()==null||p.getDataValues().get(0).getValue().toString().isEmpty())continue;
            queryParams.addQueryParams(p);
        }
        if(!BaseChecks.hasEmptyStr(xm)){
            queryParams.addQueryParams(Parameter.createParameter("realname", EOperators.类似, BaseChecks.bothEndsStr(xm)));
        }
//        queryParams.addQueryParams(Parameter.createParameter("deleted","0"));
        queryParams.addOrderColumns("addtime desc");
        try {
            queryParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> result = baseDaoComponent.selectDataByParams(queryParams);
        queryParams.printSelf();

        //导出用户列表excel
        FileInfoPo fileInfoPo = FileIOComponent.createTempFilePathByType(FileIOComponent.EXPORT_TYPE,"xlsx","公共管理-用户管理");
        Map<String, Object> filePath = new HashMap<>();
        filePath.put("url", fileInfoPo.getFileVirPath());
        //写入excel表格
        //     ExportExcel excelHelper = ExportExcel.createExportExcel(absPath,"{index:序号,DISTRICTCODE:区县代码,SCHOOLNAME:学校名称,ENAME:帐号,ROLETYPE:权限,REALNAME:姓名,SFZJH:身份证号,EMAIL:邮箱,MOBILE:手机,DELETED:状态}");
        ExportExcel excelHelper = ExportExcel.createExportExcel(fileInfoPo.getFileAbsPath(),"{index:序号,districtname:区县,schoolcode:学校代码,schoolname:学校名称,ename:用户名,roletype:角色,realname:姓名,sfzjh:身份证号,email:邮箱,mobile:手机,deleted:状态}");
        //写入表头
        //写入正文
        for (int i =0,size = result.size();i<size;i++){
            Map<String,Object> data = result.get(i);
            try {
                result.get(i).put("index",i+1);
                result.get(i).put("DISTRICTNAME",data.get("DISTRICTNAME")==null?null:data.get("DISTRICTNAME").toString());
                result.get(i).put("SCHOOLNAME",data.get("SCHOOLNAME")==null?null:data.get("SCHOOLNAME").toString());
                result.get(i).put("ENAME", data.get("ENAME")==null?null:data.get("ENAME").toString());
                result.get(i).put("ROLETYPE",getRoleTypeName(data.get("ROLETYPE")==null?null:data.get("ROLETYPE").toString()));
                result.get(i).put("REALNAME",data.get("REALNAME")==null?null:data.get("REALNAME").toString());
                result.get(i).put("SFZJH",data.get("SFZJH")==null?null:data.get("SFZJH").toString());
                result.get(i).put("EMAIL",data.get("EMAIL")==null?null:data.get("EMAIL").toString());
                result.get(i).put("MOBILE",data.get("MOBILE")==null?null:data.get("MOBILE").toString());
                result.get(i).put("DELETED",data.get("DELETED").toString().equals("0")?"正常":"已注销");
            }catch(Exception e){}
        }
        excelHelper.setCurrentData(result);
        excelHelper.writeCurrentData();
        JSONObject rs = ResponseUtils.createSuccessResponseBody("导出成功", filePath);
        return rs;
    }

    public String getRoleTypeName(String roleType){
        if("0".equals(roleType)) return "系统管理员";
        if("1".equals(roleType)) return "教育局管理员";
        if("2".equals(roleType)) return "区县管理员";
        if("3".equals(roleType)) return "学校管理员";
        else return "";
    }

    /** 查看用户详细信息 **/
    @Override
    public JSONObject queryAdminUserInformation(Map<String, Object> params) throws SQLException, DataNotFoundException {
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        QueryParams queryParams = QueryParams.createQueryParams("V_M45_ADMINDETAIL_NK");
        queryParams.addQueryParams(Parameter.createParameter("id", params.get("id")));
        try {
            queryParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> result = baseDaoComponent.selectDataByParams(queryParams);
        if (result == null || result.isEmpty()) throw new DataNotFoundException();
    //    result.get(0).put("schoolid", StaticCaches.getSchoolNameBySchoolId((String) result.get(0).get("schoolid")));
        JSONObject rs = ResponseUtils.createSuccessResponseBody("done", result.get(0));
        return rs;
    }

    /** 修改用户信息 **/
    @Override
    public JSONObject updateUserInformation(Map<String, Object> params) throws SQLException, BaseException {
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        //1.1:校验身份证、手机号和邮箱的唯一性
        //1.2:角色修改和信息修改用同一个接口
        //校验重复身份证
        String id = (String) params.get("id");
        String sfzjh = (String) params.get("sfzjh");
        String mobile = (String) params.get("mobile");
        String email = (String) params.get("email");
        String adminid = (String) params.get("adminid");
        String districtcode = (String) params.get("districtcode");
        String schoolcode = (String) params.get("schoolcode");
        String roleid = (String) params.get("roleid");
        String realname = (String) params.get("realname");
        QueryParams queryParams = QueryParams.createQueryParams("T_ADMININFO");
        queryParams.addColumns("id");
        queryParams.addQueryParams(Parameter.createParameter("sfzjh",sfzjh), Parameter.createParameter("id", EOperators.不包含,id));
        try {
            queryParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> checkSfzjh = baseDaoComponent.selectDataByParams(queryParams);
        if(!checkSfzjh.isEmpty())throw new ValidateSameSfzjhException();
        //校验重复手机号
        QueryParams queryParams1 = QueryParams.createQueryParams("T_ADMININFO");
        queryParams1.addColumns("id");
        queryParams1.addQueryParams(Parameter.createParameter("mobile",mobile), Parameter.createParameter("id", EOperators.不包含,id));

        //校验合法性
        //校验姓名，必须为中文
        String regx = "^[\\u4E00-\\u9FFF]+$";
        Pattern pattern = Pattern.compile(regx);
        Matcher matcher = pattern.matcher(realname);
        if(!matcher.matches())throw new DistrictIdException(20049);

        //校验联系电话，11位首位不为0
        regx = "^1[0-9]{10}$";
        pattern = Pattern.compile(regx);
        matcher = pattern.matcher(mobile);
        if(!matcher.matches())throw new DistrictIdException(20050);

        //校验邮箱，符合邮箱规则
        regx = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        pattern = Pattern.compile(regx);
        matcher = pattern.matcher(email);
        if(!matcher.matches())throw new DistrictIdException(20051);

        try {
            queryParams1.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> checkMobile = baseDaoComponent.selectDataByParams(queryParams1);
        if(!checkMobile.isEmpty())throw new ValidateSameMobileException();
        //校验重复邮箱
        QueryParams queryParams2 = QueryParams.createQueryParams("T_ADMININFO");
        queryParams2.addColumns("id");
        queryParams2.addQueryParams(Parameter.createParameter("email",email), Parameter.createParameter("id", EOperators.不包含,id));
        try {
            queryParams2.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> checkEmail = baseDaoComponent.selectDataByParams(queryParams2);
        if(!checkEmail.isEmpty())throw new ValidateSameEmailException();
        //修改用户信息
        UpdateParams updateParams = UpdateParams.createUpdateParams("T_ADMININFO");
        updateParams.addWhereParameter(Parameter.createParameter("id",id));
        updateParams.addParams(Parameter.createParameter("sfzjh",sfzjh),
                Parameter.createParameter("mobile",mobile),
                Parameter.createParameter("email",email),
                createParameter("UPDATETIME", Format.getDateTime()),
                Parameter.createParameter("UPDATEUSERID",adminid));
        //判断参数是否为空,为空的使用原数据
        if(!BaseChecks.hasEmptyStr(districtcode))updateParams.addParams(Parameter.createParameter("districtcode",districtcode));
        if(!BaseChecks.hasEmptyStr(schoolcode))updateParams.addParams(Parameter.createParameter("schoolcode",schoolcode));
        if(!BaseChecks.hasEmptyStr(roleid))updateParams.addParams(Parameter.createParameter("roleid",roleid));
        if(!BaseChecks.hasEmptyStr(realname))updateParams.addParams(Parameter.createParameter("realname",realname));
        updateParams.printSelf();
        try {
            updateParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int i = baseDaoComponent.updateDataByParams(updateParams);
        if(i==0)throw new DataNotFoundException();
        JSONObject rs = ResponseUtils.createSuccessResponseBody("修改成功");
        return rs;
    }

    /** 新增用户 **/
    @Override
    public JSONObject addAdminUser(Map<String, Object> params) throws Exception {
        //校验用户名是否重复!
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        QueryParams queryName =  QueryParams.createQueryParams("T_ADMININFO");
        queryName.addColumns("id");
        queryName.addQueryParams(Parameter.createParameter("ename",params.get("ename")));
        try {
            queryName.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> listName = baseDaoComponent.selectDataByParams(queryName);
        if(listName.size() > 0 ) throw  new UserNameException();
        //校验重复身份证
        QueryParams queryParams = QueryParams.createQueryParams("T_ADMININFO");
        queryParams.addColumns("id");queryParams.addQueryParams(Parameter.createParameter("sfzjh",params.get("sfzjh")));
        try {
            queryParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> checkSfzjh = baseDaoComponent.selectDataByParams(queryParams);
        if(!checkSfzjh.isEmpty())throw new ValidateSameSfzjhException();
        //校验重复手机号
        QueryParams queryParams1 = QueryParams.createQueryParams("T_ADMININFO");
        queryParams1.addColumns("id");queryParams1.addQueryParams(Parameter.createParameter("mobile",params.get("mobile")));
        try {
            queryParams1.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> checkMobile = baseDaoComponent.selectDataByParams(queryParams1);
        if(!checkMobile.isEmpty())throw new ValidateSameMobileException();
        //校验重复邮箱
        QueryParams queryParams2 = QueryParams.createQueryParams("T_ADMININFO");
        queryParams2.addColumns("id");queryParams2.addQueryParams(Parameter.createParameter("email",params.get("email")));
        try {
            queryParams2.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> checkEmail = baseDaoComponent.selectDataByParams(queryParams2);
        if(!checkEmail.isEmpty())throw new ValidateSameEmailException();

        //验证区县是否正确. DistrictIdException
        if(!params.get("roletype").equals("1")){
            String districtcode = DataDict.getChineseValueByCode(EStandTables.区县表, (String) params.get("districtcode"));
            if(districtcode.isEmpty())throw new DistrictIdException(20045);
        }

        //校验用户名是否为字母数字组合，首位必须为字母且大于八位，否抛出异常
        String ename = (String) params.get("ename");
        String regx = "^[a-zA-Z][a-zA-Z0-9]{8,30}$";
        Pattern pattern = Pattern.compile(regx);
        Matcher matcher = pattern.matcher(ename);
        if(!matcher.matches())throw new DistrictIdException(20046);

        //校验姓名，必须为中文
        String realname = (String) params.get("realname");
        regx = "^[\\u4E00-\\u9FFF]+$";
        pattern = Pattern.compile(regx);
        matcher = pattern.matcher(realname);
        if(!matcher.matches())throw new DistrictIdException(20049);

        //校验联系电话，11位首位不为0
        String mobile = (String) params.get("mobile");
        regx = "^1[0-9]{10}$";
        pattern = Pattern.compile(regx);
        matcher = pattern.matcher(mobile);
        if(!matcher.matches())throw new DistrictIdException(20050);

        //校验邮箱，符合邮箱规则
        String email = (String) params.get("email");
        regx = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
        pattern = Pattern.compile(regx);
        matcher = pattern.matcher(email);
        if(!matcher.matches())throw new DistrictIdException(20051);

        String uuid = UUID.randomUUID().toString();
        String passw = StringUtils.getRandomStr(8)+"123456"+StringUtils.getRandomStr(6);
        //开始新增用户
     /*   String districtcode = (String)params.get("districtcode")==null||((String) params.get("districtcode")).isEmpty()?null:(String)params.get("districtcode");*/
        InsertParams insertParams = InsertParams.createInsertParams("T_ADMININFO","ID","ENAME","CIPHERTEXT","CIPHERTEXTMD","REALNAME","SFZJH","MOBILE","EMAIL","LOGINCNT","LOGINTIME","LASTLOGINTIME","ROLEID","DISTRICTCODE","SCHOOLCODE","ADDUSERID","ADDTIME","UPDATEUSERID","UPDATETIME","DELETED","DELETEDTIME","REMARK");
        insertParams.setValues(uuid,params.get("ename"),passw, Encrypt.jiam("123456"),params.get("realname"),params.get("sfzjh"),params.get("mobile"),
                params.get("email"),0,null,null,params.get("roleid"), params.get("districtcode"),params.get("schoolcode"),
                params.get("adminid"), Format.getDateTime(),null,null,0,null,null);
        try {
            insertParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        baseDaoComponent.insertDataByParams(insertParams);
        JSONObject rs = ResponseUtils.createSuccessResponseBody("添加用户成功");
        return rs;
    }

    /** 注销用户 **/
    @Override
    public JSONObject cancelAdminUser(Map<String, Object> params) throws SQLException, DataNotFoundException, DistrictIdException {
        //将用户状态修改为1
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        String adminid = (String) params.get("adminid");//操作人id
        UpdateParams updateParams = UpdateParams.createUpdateParams("T_ADMININFO");
        updateParams.addWhereParameter(Parameter.createParameter("id",params.get("id")));
        updateParams.addParams(Parameter.createParameter("deleted","1"),
                createParameter("deletedtime",Format.getDateTime()),
                Parameter.createParameter("updateuserid",adminid),
                createParameter("updatetime",Format.getDateTime()));
        try {
            updateParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int i = baseDaoComponent.updateDataByParams(updateParams);
        if(i==0)throw new DataNotFoundException();
        JSONObject rs = ResponseUtils.createSuccessResponseBody("注销成功");
        return rs;
    }

    /** 恢复用户 **/
    @Override
    public JSONObject recoveryAdminUser(Map<String, Object> params) throws SQLException, BaseException {
        //将用户状态修改为0，被注销的学校其下管理员不能恢复
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        String adminid = (String) params.get("adminid");  //操作人id

        QueryParams queryParams = QueryParams.createQueryParams("V_M45_ADMINDETAIL_NK");
        queryParams.addQueryParams(Parameter.createParameter("id",params.get("id")));
        try {
            queryParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> result = baseDaoComponent.selectDataByParams(queryParams);
        String schdel = (String) result.get(0).get("schdeleted");    //判断学校是否注销
        if("1".equals(schdel)){     //已注销
            throw new BaseException(80004);
        }else{
            UpdateParams updateParams = UpdateParams.createUpdateParams("T_ADMININFO");
            updateParams.addWhereParameter(Parameter.createParameter("id",params.get("id")));
            updateParams.addParams(Parameter.createParameter("deleted","0"),
                    Parameter.createParameter("deletedtime",""),
                    Parameter.createParameter("updateuserid",adminid),
                    createParameter("updatetime",Format.getDateTime()));
            try {
                updateParams.setDbLog(loginInfo);
            } catch (Exception e) {
                e.printStackTrace();
            }
            int i = baseDaoComponent.updateDataByParams(updateParams);
            if(i==0)throw new DataNotFoundException();
            JSONObject rs = ResponseUtils.createSuccessResponseBody("恢复成功");
            return rs;
        }
    }

    /** 清除用户邮箱 **/
    @Override
    public JSONObject clearUserEmail(Map<String,Object> params)throws SQLException,DataNotFoundException{
        //参数:id:用户id
        //已清除的邮箱的用户,不能重复清除
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        QueryParams queryParams1 = QueryParams.createQueryParams("t_adminInfo");
        queryParams1.addQueryParams(Parameter.createParameter("id",params.get("id")));
        queryParams1.addColumns("id","email");
        try {
            queryParams1.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> mapList = baseDaoComponent.selectDataByParams(queryParams1);
        if(mapList.isEmpty())throw new DataNotFoundException();
        if(mapList.get(0).get("email")==null || "".equals(mapList.get(0).get("email")))throw new DataNotFoundException();
        //开始清除邮箱
        UpdateParams updateParams = UpdateParams.createUpdateParams("t_adminInfo");
        updateParams.addWhereParameter(Parameter.createParameter("id",params.get("id")));
        updateParams.addParams(Parameter.createParameter("email",""),
                Parameter.createParameter("updateuserid",params.get("adminid")),
                Parameter.createParameter("updatetime",Format.getDateTime()));
        try {
            updateParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int i = baseDaoComponent.updateDataByParams(updateParams);
        if(i==0)throw new DataNotFoundException();
        return ResponseUtils.createSuccessResponseBody("清除用户邮箱成功");
    }

    /** 重置用户密码 **/
    @Override
    public JSONObject recoverUserPwd(Map<String,Object> params) throws Exception {
        //参数:id:用户id
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        String passw = StringUtils.getRandomStr(8)+"123456"+StringUtils.getRandomStr(6);
        UpdateParams updateParams = UpdateParams.createUpdateParams("t_adminInfo");
        updateParams.addWhereParameter(Parameter.createParameter("id",params.get("id")));
        updateParams.addParam(Parameter.createParameter("CIPHERTEXTMD",Encrypt.jiam("123456")));
        updateParams.addParams(Parameter.createParameter("CIPHERTEXT",passw),
                Parameter.createParameter("updateuserid",params.get("adminid")),
                Parameter.createParameter("updatetime",Format.getDateTime()));
        try {
            updateParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int i = baseDaoComponent.updateDataByParams(updateParams);
        if(i==0)throw new DataNotFoundException();
        return ResponseUtils.createSuccessResponseBody("用户密码重置成功,密码是:123456,请尽快修改密码");
    }

    /** 修改管理员密码 **/
    @Override
    public JSONObject modifyAdminPwd(Map<String,Object> params) throws Exception {
        //参数:id:用户adminid  ,newpwd ,    oldpwd
        //密码规则：同时包含大小写字母和数字，至少八位
        //1.1:查询管理员旧密码
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        QueryParams queryParams1 = QueryParams.createQueryParams("t_admininfo");
        queryParams1.addQueryParams(Parameter.createParameter("id",params.get("adminid")));
            queryParams1.addColumns("CIPHERTEXT");    //查旧明文密码
        try {
            queryParams1.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String,Object>> mapList = baseDaoComponent.selectDataByParams(queryParams1);
        if(mapList.isEmpty())throw new DataNotFoundException();
        //1.2:判断管理员旧密码是否正确
        String pwd = (String) mapList.get(0).get("CIPHERTEXT");    //有随机位的密码
        String pwd1 = pwd.substring(8);
        pwd1 = pwd1.substring(0,pwd1.length()-6);   //明文密码
        String oldpwd = (String) params.get("oldpwd");
        if(!pwd1.equals(oldpwd))throw new LaunchCommitException(20071);
        //验证：新密码与旧密码不能相同
        String newpwd = (String)params.get("newpwd");    //新密码
        if(newpwd.equals(oldpwd)){
            throw new PasswordSameException();
        }
        //验证：新密码必须符合规则 前端限制
        String regx = "^(?=.*\\d)(?=.*[a-z])(?=.*[A-Z]).{8,30}$";
        Pattern pattern = Pattern.compile(regx);
        Matcher matcher = pattern.matcher(newpwd);
        if(!matcher.matches())throw new DistrictIdException(20048) ;

        String newpwd1 = StringUtils.getRandomStr(8)+newpwd+StringUtils.getRandomStr(6);
        //1.3:修改管理员密码
        UpdateParams updateParams = UpdateParams.createUpdateParams("t_admininfo");
        updateParams.addWhereParameter(Parameter.createParameter("id",params.get("adminid")));
        updateParams.addParam(Parameter.createParameter("CIPHERTEXT",newpwd1));
        updateParams.addParam(Parameter.createParameter("CIPHERTEXTMD",Encrypt.jiam((String) params.get("newpwd"))));
        updateParams.addParam(Parameter.createParameter("updatetime",Format.getDateTime()));
        updateParams.addParam(Parameter.createParameter("updateuserid",params.get("adminid")));
        //用户修改密码时间 2016-12-16
        updateParams.addParam(Parameter.createParameter("modifyPassWordTime",Format.getDateTimeLong()));
        try {
            updateParams.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int i = baseDaoComponent.updateDataByParams(updateParams);
        if(i==0)throw new DataNotFoundException();
        return ResponseUtils.createSuccessResponseBody("修改成功");
    }

    /**
     * 　根据角色类型获取角色
     **/
    public JSONObject getRoleByRoleType(Map<String, Object> params) throws SQLException, DataNotFoundException {
        //参数: roletype
        //返回: roleid rolename
        LoginInfo loginInfo = (LoginInfo) params.remove("userinfo");
        String roleType = (String) params.get("roletype");
        if (params.get("roletype") == null || "".equals(params.get("roletype"))) throw new DataNotFoundException();
        QueryParams queryParams3 = QueryParams.createQueryParams("VD_GETROLEBYROLETYPE_NK");
        String districtcode = loginInfo.getDistrictcode();
        if(districtcode == null || districtcode.isEmpty()){   //市级查询，没districtcode
            queryParams3.addQueryParams(Parameter.createParameter("roletype",roleType));
        }else{
            Parameter dsid = Parameter.createParameter("districtcode", loginInfo.getDistrictcode());
            Parameter nullDs = Parameter.createParameter("districtcode", EOperators.为空, null);
            nullDs.setAnd(false);
            Parameter rtype = Parameter.createParameter("roletype", roleType);
            Parameter crttype = Parameter.createParameter("roletype", roleType);
            crttype.setSpeator(2);
            rtype.setSpeator(2);
            dsid.setSpeator(1);
            nullDs.setSpeator(1);
            queryParams3.addQueryParams(dsid, crttype);
            queryParams3.addQueryParams(nullDs, rtype);
        }
        try {
            queryParams3.setDbLog(loginInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }
        List<Map<String, Object>> mapList = baseDaoComponent.selectDataByParams(queryParams3);
        return ResponseUtils.createSuccessResponseBody("查询成功", mapList);
    }
}
